# !/usr/bin/env python
# -*- coding: utf-8 -*-
# ///////////////////////////////////////////////////////////////
# @File    :   getImageBaseData.py
# @Time    :   2024/08/21 14:39:56
# @Author  :   kai.luo
# @Version :   1.0.0
# @Desc    :   获取医疗图片中检查项目的公共库
# ///////////////////////////////////////////////////////////////

import re
import copy
import traceback
from moudles.MedicalReportForm.commonLibrary.common import *


class MainInfo(object):
    """
    项目,结果,单位,参考区间,提示
    Args:
        object (_type_): _description_
    """

    def __init__(self, **kwarg) -> None:
        # 初始化参数
        self.main_title = ['项目', '结果', '单位', '参考区间', '提示']

    def parserMainTitleIndex(self, data):
        """
        获取有效项目标题的下标
        Args:
            data (_type_): _description_
        """
        # print(f'parserMainTitleIndex---{data}')
        # 获取有效的标题所在X轴的排序
        main_title_indx_list = list()
        for indx, item in enumerate(data):
            text = item[1][0]
            if re.findall(r'项目', text):
                main_title_indx_list.append(indx)
            elif re.findall(r'结果|测定值', text):
                main_title_indx_list.append(indx)
            elif re.findall(r'单位', text):
                main_title_indx_list.append(indx)
            elif re.findall(r'参考区间|检测下限|参考范围', text):
                main_title_indx_list.append(indx)

        return main_title_indx_list

    def getMainLineData(self, data: list):
        all_line_data_list = []  # 所有行的数据
        line_data_list = []  # 每行含坐标数据
        compare_y = ''

        for indx, item in enumerate(data):
            x, y = item[0][0]
            text = item[1][0]
            if indx == 0:
                compare_y = y
                line_data_list.append(item)
            else:
                if abs(compare_y-y) <= 13:  # 保证在同一行
                    line_data_list.append(item)
                else:
                    all_line_data_list.append(line_data_list)
                    compare_y = y
                    line_data_list = []
                    line_data_list.append(item)

        return all_line_data_list

    def fixedLinePosxData(self, all_line_data_list: list):
        """
        每一行数据中，每项末尾坐标X与相邻参数数据坐标太近，默认是同一个参数
        Args:
            all_line_data_list (list): _description_
        """
        max_len = 0  # 项目最大长度
        all_lines = list()  # 所有行
        for line_list in all_line_data_list:
            new_line_list = copy.deepcopy(line_list)
            # 筛选数据
            for indx in range(len(line_list)-1):
                try:
                    # rigth_bottom的x坐标与left_bottom的x坐标距离小于8，视为不应该分离
                    rigth_bottom_x, left_bottom_y = line_list[indx][0][2]
                    rigth_bottom_x_2, left_bottom_y_2 = line_list[indx+1][0][3]
                    if abs(rigth_bottom_x_2 - rigth_bottom_x) < 8:
                        new_line_list.pop(indx+1)
                except:
                    print(traceback.print_exc())
                    print(f'fixedLinePosxData-line_list----{line_list}')

            # 添加数据
            all_lines.append(new_line_list)

            # 获取最大行
            if max_len < len(new_line_list):
                max_len = len(new_line_list)

        return max_len, all_lines

    def getMainLineList(self,  max_len: int, max_line_posx_list: list, data: list,):
        """
        对项目每一行的数据进行查缺补漏
        Args:
            max_len (int): 项目最大长度
            max_line_posx_list (list): 最长行的x坐标值列表
            data (list): 所有项目数据

        Returns:
            _type_: _description_
        """
        mainLines = list()

        for indx, line_data in enumerate(data):
            entry_data = list()
            temp_index = 0
            insert_indx_list = []  # 需要插入位置的列表
            try:
                if len(line_data) != max_len:
                    for index, reference_pox in enumerate(max_line_posx_list):
                        temp_posx, temp_posy = line_data[temp_index][0][0]
                        if abs(temp_posx - reference_pox) > 38:  # 需要插入的位置
                            insert_indx_list.append(index)
                        else:
                            if len(line_data)-1 <= temp_index:  # 缺少最后项
                                continue
                            else:
                                temp_index += 1
            except:
                print(traceback.print_exc())

            # 获取纯文本的一行数据
            try:
                for line in line_data:
                    text = line[1][0]
                    entry_data.append(text)
            except:
                print(traceback.print_exc())

            # 数据补漏
            try:
                if len(entry_data) != max_len:
                    for insert_indx in insert_indx_list:
                        if insert_indx == 0:
                            entry_data.insert(insert_indx, '0')
                        else:
                            entry_data.insert(insert_indx, '')
                    mainLines.append(entry_data)
                else:
                    mainLines.append(entry_data)
            except:
                print(traceback.print_exc())

        return mainLines

    def filterMainDisplayEntrys(self, display_col_index_list: list, mainLines: list):
        """
        过滤出需要展示列数据
        Args:
            display_col_index_list (list): 需要展示列所在所有列的下标
            mainLines (list): 所有列的数据

        Returns:
            _type_: _description_
        """
        mainContextsList = list()
        for indx, item in enumerate(mainLines):
            # print(f'item---{item}')
            try:
                mainEntrysList = list()
                for main_title_indx in display_col_index_list:
                    mainEntrysList.append(item[main_title_indx])
                mainContextsList.append(mainEntrysList)
            except:
                print(traceback.print_exc())

        return mainContextsList

    def filterEffectiveLines(self, data: list):
        """
        过滤出有效行
        Args:
            data (list): _description_
        """
        new_data = list()
        for item in data:
            if item[0]:
                new_data.append(item)

        return new_data

    def mainResultEntrys(self, data: list):
        """
        根据结果与参考值的对比，得出检验结果
        Args:
            data (list): _description_

        Returns:
            _type_: _description_
        """
        for item in data:
            # 获取
            try:
                # 检验值
                if re.findall(r'^未见', item[1].strip()):
                    item.append('正常')
                    continue
                res_val_list = re.findall(r'[0-9]+\.*[0-9]*', item[1])
                temp_res_val_list = [x for x in res_val_list if x != '0']
                res_val = ''.join(temp_res_val_list)
            except:
                res_val = float(0)
            finally:
                if res_val == float(0):
                    item.append('')
                    continue

            try:
                reference_val = item[3]  # 参考值
                if not reference_val:
                    item.append('')
                    continue
                # 有值的情况
                if '-' in reference_val:
                    min_val, max_val = reference_val.split('-')
                    if float(res_val) >= float(min_val) and float(res_val) <= float(max_val):
                        item.append('正常')
                    else:
                        if float(res_val) < float(min_val):
                            item.append('偏低')
                        elif float(res_val) > float(max_val):
                            item.append('偏高')
                else:
                    reference_val_list = re.findall(r'[0-9]+\.*[0-9]*', item[3])
                    temp_reference_val_list = [x for x in reference_val_list if x != '0']
                    reference_val = ''.join(temp_reference_val_list)
                    if '<' in reference_val:
                        if float(res_val) > float(reference_val):
                            item.append('偏高')
                        else:
                            item.append('正常')
                    elif '>' in reference_val:
                        if float(res_val) < float(reference_val):
                            item.append('偏低')
                        else:
                            item.append('正常')
                    else:
                        item.append('')
            except:
                print(traceback.print_exc())

        return data

    # def parserMainContexts(self, data):
    #     """
    #     普遍性检验报告
    #     Args:
    #         data (_type_): _description_
    #     """
    #     # print(f'parserMainContexts---{data}')

    #     # 纠正无意义的符号参杂在一行列表中
    #     fixed_data = fixedLineList(data)

    #     # 解析数据，获取最大的有效行及最大有效行的所有元素的x坐标及每行进行纠正后的排序
    #     max_len, line_item_list, sort_x_data = self.parserLines(fixed_data)

    #     # 对项目每一行的数据进行查缺补漏
    #     mainLines = self.getMainLineList(sort_x_data, max_len, line_item_list)

    #     # 获取项目每一行数据值的列表
    #     mainContextsList = self.getMainEntrys(mainLines)
    #     # print(f'self.main_title_indx_list---{self.main_title_indx_list}')
    #     # print(f'mainContextsList---{mainContextsList}')

    #     # 根据每行数据，得出检验结果
    #     mainEntrysContexts = self.mainResultEntrys(mainContextsList)
    #     # print(f'mainEntrysContexts---{mainEntrysContexts}')
    #     return mainEntrysContexts

    # def parserLines(self, data: list):
    #     """
    #     获取最大的有效行
    #     最大有效行的所有元素的x坐标
    #     每行进行纠正后的排序
    #     Args:
    #         data (list): _description_
    #     """
    #     max_len = 0  # 最大长度
    #     line_data_list = []  # 含坐标数据的集合
    #     line_data = []  # 每行含坐标数据
    #     compare_y = ''

    #     for indx, item in enumerate(data):
    #         x, y = item[0][0]
    #         text = item[1][0]
    #         if indx == 0:
    #             compare_y = y
    #             line_data.append(item)
    #         else:
    #             if abs(compare_y-y) <= 13:  # 保证在同一行
    #                 line_data.append(item)
    #             else:
    #                 if max_len < len(line_data):
    #                     max_len = len(line_data)

    #                 line_data_list.append(line_data)
    #                 compare_y = y
    #                 line_data = []
    #                 line_data.append(item)

    #     # 根据x轴的大小进行排序
    #     sort_x_data = sortedData(line_data_list)

    #     # 随机抽查最大行的数据
    #     max_line_items = []
    #     for index, line_list in enumerate(sort_x_data):
    #         if max_len == len(line_list):
    #             for line in line_list:
    #                 x, y = line[0][0]
    #                 max_line_items.append(x)
    #             break

    #     return max_len, max_line_items, sort_x_data

    # def getMainLineList(self, data: list, max_len: int, item_pox_list: list):
    #     """
    #     对项目每一行的数据进行查缺补漏
    #     Args:
    #         data (list): _description_
    #     """
    #     mainLines = list()

    #     for indx, line_data in enumerate(data):
    #         entry_data = list()
    #         temp_index = 0
    #         insert_indx_list = []  # 需要插入位置的列表
    #         if len(line_data) != max_len:
    #             for index, item_pox in enumerate(item_pox_list):
    #                 temp_posx, temp_posy = line_data[temp_index][0][0]
    #                 if abs(temp_posx - item_pox) > 38:
    #                     insert_indx_list.append(index)
    #                 else:
    #                     temp_index += 1
    #         # 获取纯文本的一行数据
    #         for line in line_data:
    #             text = line[1][0]
    #             entry_data.append(text)

    #         # 数据补漏
    #         if len(entry_data) != max_len:
    #             for insert_indx in insert_indx_list:
    #                 if insert_indx == 0:
    #                     entry_data.insert(insert_indx, '0')
    #                 else:
    #                     entry_data.insert(insert_indx, '')
    #             mainLines.append(entry_data)
    #         else:
    #             mainLines.append(entry_data)

    #     return mainLines

    # def mainResultEntrys(self, data: list):
    #     """_summary_
    #     """
    #     for item in data:
    #         try:
    #             # 检验值
    #             res_val_list = re.findall(r'[0-9]+\.*[0-9]*', item[1])
    #             temp_res_val_list = [x for x in res_val_list if x != '0']
    #             res_val = ''.join(temp_res_val_list)
    #         except:
    #             res_val = float(0)
    #         finally:
    #             if res_val == float(0):
    #                 item.append('')
    #                 continue

    #         reference_val = item[3]  # 参考值
    #         if not reference_val:
    #             item.append('')
    #             continue
    #         # 有值的情况
    #         if '-' in reference_val:
    #             min_val, max_val = reference_val.split('-')
    #             if float(res_val) >= float(min_val) and float(res_val) <= float(max_val):
    #                 item.append('正常')
    #             else:
    #                 if float(res_val) < float(min_val):
    #                     item.append('偏低')
    #                 elif float(res_val) > float(max_val):
    #                     item.append('偏高')
    #         else:
    #             reference_val_list = re.findall(r'[0-9]+\.*[0-9]*', item[3])
    #             temp_reference_val_list = [x for x in reference_val_list if x != '0']
    #             reference_val = ''.join(temp_reference_val_list)
    #             if '<' in reference_val:
    #                 if float(res_val) > float(reference_val):
    #                     item.append('偏高')
    #                 else:
    #                     item.append('正常')
    #             elif '>' in reference_val:
    #                 if float(res_val) < float(reference_val):
    #                     item.append('偏低')
    #                 else:
    #                     item.append('正常')
    #             else:
    #                 item.append('')

    #     return data
